"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '07/09/2022'
    comment: 封装的最底层函数
"""
import datetime
from decimal import Decimal
from typing import Optional, Union
from enum import Enum


def serializer(
    data: Optional[Union[tuple, list, set, dict]]
) -> Optional[Union[dict, list]]:
    """递归序列化: 有几种基本类型, 比如时间,日期, decimal 需要序列化
    :param data:
    :return:
    """
    if data is None:
        return None

    # 如果是list或者tuple set
    if isinstance(data, (tuple, list, set)):
        dicts = []
        for each in data:
            dicts.append(serializer(each))
        return dicts
    # 不是dict 就直接返回
    if not isinstance(data, dict):
        return data
    # 将字典中的各种不能序列号的类型转化成字符串
    result_data = {}
    for key, value in data.items():
        if isinstance(value, (tuple, list, dict)):
            # 如果值是list, tuple, dict, 那么需要遍历下去
            result_data[key] = serializer(value)
        elif isinstance(value, datetime.datetime):
            result_data[key] = value.strftime("%Y-%m-%d %H:%M:%S")
            result_data[key + '_' + 'ts'] = int(value.timestamp())
        elif isinstance(value, datetime.date):
            result_data[key] = value.strftime("%Y-%m-%d")
        elif isinstance(value, datetime.time):
            result_data[key] = value.strftime("%H:%M:%S")
        elif isinstance(value, Decimal):
            result_data[key] = str(value)
        elif isinstance(value, Enum):
            result_data[key] = value.value
        else:
            result_data[key] = value

    return result_data
